//
//  KDRectanglesProgress.m
//  WangJingApp
//
//  Created by 魏强 on 17/1/10.
//  Copyright © 2017年 KDTech. All rights reserved.
//  长方形进度条

#import "KDRectanglesProgress.h"
static CGFloat const persentageLb_W = 35;
@interface KDRectanglesProgress ()
@property (strong, nonatomic) CAShapeLayer *maskLayer; // 顶部遮罩
/**  进度条显示label */
@property (nonatomic, weak) UILabel *persentageLb;


@end
@implementation KDRectanglesProgress
#pragma mark - 懒加载区

#pragma mark set/get方法区
- (void)setPersentage:(CGFloat)persentage{
    if (persentage < 0) return;
    _persentage = persentage;
    self.persentageLb.text = [self floatToPercent:persentage];
    [self setNeedsLayout];
}

- (void)setShowPersentageLb:(BOOL)showPersentageLb{
    _showPersentageLb = showPersentageLb;
    [self setNeedsLayout];
}
#pragma mark - 生命周期区
- (void)layoutSubviews{
    [super layoutSubviews];
    self.maskLayer.backgroundColor = self.color.CGColor;
    CGRect frame =  self.maskLayer.bounds;
    frame.size.width = _persentage *(self.width - persentageLb_W);
    self.maskLayer.frame = frame;
    //如果显示，就显示label的数据，如果不显示，就直接颜色为白色的效果（就看不见了）
    self.persentageLb.textColor = (_showPersentageLb)? self.color:[UIColor whiteColor];
    
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initialize];
    }
    return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self initialize];
    }
    return self;
}
#pragma mark - 板块布置区
/**
 *  设置底部layer
 */
- (void)setupMaskLayer{
    if (!self.maskLayer) {//如果不存在就创建一个
        self.maskLayer = [CAShapeLayer layer];
        CGRect frame = self.bounds;
        frame.size.width = self.bounds.size.width - persentageLb_W;
        self.maskLayer.frame = frame;
        [self.layer addSublayer:self.maskLayer];
    }
    
}


- (void)initialize{
    self.backgroundColor = [UIColor lightGrayColor];
    self.showPersentageLb = YES;
    [self setupMaskLayer];
    [self setupLabel];
}
/**
 *  初始化百分比label
 */
- (void)setupLabel{
    UILabel *label = [[UILabel alloc]init];
    [self addSubview: label];
    label.frame = CGRectMake(self.width - persentageLb_W, 0, persentageLb_W, self.height);
    label.backgroundColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentRight;
    label.font = [UIFont systemFontOfSize:14];
    self.persentageLb = label;
}
#pragma mark - 事件点击区

#pragma mark - 网络请求区

#pragma mark - 通知接收区


/**
 *  小数点转百分比
 *
 *  @return 返回百分比
 */
- (NSString *)floatToPercent:(CGFloat )floutNumber{
    NSNumberFormatter *hereNumFormatter = [[NSNumberFormatter alloc] init];
    [hereNumFormatter setNumberStyle:NSNumberFormatterPercentStyle];
    NSString *str = [hereNumFormatter stringFromNumber:[NSNumber numberWithDouble:floutNumber]];
    return str;
}
@end
